#include "courier_main.h"
#include "ui_courier_main.h"

Courier_main::Courier_main(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Courier_main)
{
    ui->setupUi(this);
    this->setFixedSize(440,720);
    save_page = new Courier_savestg(this);
    qDebug()<<"12121212";
    save_page->hide();
    socket = SocketManager::getinstance().socket();

//    connect(socket,&QAbstractSocket::readyRead,this,&Courier_main::showempty);
    connect(socket,&QAbstractSocket::readyRead,this,&Courier_main::f_cdata);
    connect(save_page,&Courier_savestg::finish_save,this,&Courier_main::tome);
}

Courier_main::~Courier_main()
{
    delete ui;
}

void Courier_main::flush_cdata()
{
    ui->listWidget->clear();
    sendRig meg;
    meg.type=4;
    telephone_number = Telephone_Number::teleinstance().telenum();
    strcpy(meg.tele,telephone_number.toUtf8());
    meg.IC=0;
    qDebug()<<"flush:"<<meg.tele;
    QByteArray data;
    data.append((char*)&meg,sizeof (sendRig));
    socket->write(data);

}

void Courier_main::on_pushButton_4_clicked()
{
   flush_cdata();
}

//void Courier_main::showempty()
//{
//    //显示空柜
//    if(!this->isActiveWindow()){
//        return;
//    }
//    if(flag == 0){
//        qDebug()<<"66666666666";
//        return;
//    }
//    flag =0;
//    qDebug()<<"1234567890";
//    sendRig *rd;
//    rd = (sendRig *)socket->readAll().data();

//}

void Courier_main::f_cdata()
{
    if(!this->isActiveWindow()){
        return;
    }
    sendRig  data;
    while (socket->bytesAvailable() >= sizeof(sendRig)) {
            socket->read(reinterpret_cast<char*>(&data), sizeof(sendRig));
    }
//    data = (sendRig*)socket->readAll().data();
    qDebug()<<"flushrecv:"<<data.type;
    if(data.type==4){

        QListWidgetItem * item;
        item = new QListWidgetItem;
        item->setText(QString("%1  单号: %2  %3")
                      .arg(QString::fromUtf8(data.Account))
                      .arg(QString::fromUtf8(data.ID))
                      .arg(QString::fromUtf8(data.state)));
        ui->listWidget->addItem(item);
    }
//    else if(data.type==6){
//        qDebug()<<"????????????????";
//        save_page->getstgstate(data.num,ddnum);
//        save_page->show();
//    }
}

void Courier_main::on_listWidget_itemClicked(QListWidgetItem *item)
{
    QString dddata = item->text();
    QStringList ddlist = dddata.split(' ',Qt::SkipEmptyParts);
    QString gid = QInputDialog::getText(this,"请输入验证码","请输入柜子所显示的验证码");
    sendRig data;
    strcpy(data.Account,gid.toUtf8());
    data.type=5;
    strcpy(data.ID,ddlist.at(2).toUtf8());
    ddnum = ddlist.at(2);
    qDebug()<<"ddlist[2]:"<<ddlist.at(2);
    qDebug()<<"gid:"<<gid;
    QByteArray sm;
    sm.append((char*)&data,sizeof (sendRig));
    socket->write(sm);

}

void Courier_main::tome()
{
    save_page->hide();
    this->show();
}

void Courier_main::on_pushButton_2_clicked()
{
    emit(maintoad());
}
